package com.lineage.server.datatables.sql;

import com.lineage.DatabaseFactory;
import com.lineage.server.datatables.CharObjidTable;
import com.lineage.server.datatables.ItemTable;
import com.lineage.server.datatables.lock.DwarfReading;
import com.lineage.server.datatables.storage.BoardOrimStorage;
import com.lineage.server.model.Instance.L1ItemInstance;
import com.lineage.server.templates.L1Rank;
import com.lineage.server.utils.PerformanceTimer;
import com.lineage.server.utils.SQLUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class BoardOrimTable implements BoardOrimStorage {
  private static final Log _log = LogFactory.getLog(BoardOrimTable.class);
  
  private static final List<L1Rank> _totalList = new CopyOnWriteArrayList<>();
  
  private static int _maxid = 0;
  
  public void load() {
    PerformanceTimer timer = new PerformanceTimer();
    Connection co = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    Calendar calendar = Calendar.getInstance();
    if (calendar.get(5) == 28) {
      Timestamp timestamp = new Timestamp(calendar.getTimeInMillis());
      List<L1Rank> _checkList = new CopyOnWriteArrayList<>();
      try {
        co = DatabaseFactory.get().getConnection();
        ps = co.prepareStatement(
            "SELECT * FROM `server_board_orim` WHERE `time_order`<=? ORDER BY `score` DESC");
        ps.setTimestamp(1, timestamp);
        rs = ps.executeQuery();
        while (rs.next()) {
          String[] partyMember = rs.getString("partyMember").split(",");
          List<String> checkList = new CopyOnWriteArrayList<>();
          String[] array;
          int length = (array = partyMember).length;
          int l = 0;
          while (l < length) {
            String str = array[l];
            checkList.add(str);
            l++;
          } 
          String leader = rs.getString("leader");
          int score = rs.getInt("score");
          L1Rank rank = new L1Rank(leader, checkList, score);
          _checkList.add(rank);
        } 
        List<String> _overList = new CopyOnWriteArrayList<>();
        int i = 0;
        int r = 5;
        int n = _checkList.size();
        while (i < 5 && i < n) {
          int itemCount = 0;
          if (i == 0) {
            itemCount = 3;
          } else if (i == 1 || i == 2) {
            itemCount = 2;
          } else if (i == 3 || i == 4) {
            itemCount = 1;
          } 
          L1Rank rank2 = _checkList.get(i);
          int j = 0;
          int k = rank2.getMemberSize();
          while (j < k) {
            String value = null;
            if (!_overList.contains(rank2.getPartyLeader())) {
              value = rank2.getPartyLeader();
            } else {
              Iterator<String> iterator3 = rank2.getPartyMember().iterator();
              while (iterator3.hasNext()) {
                String memberName = iterator3.next();
                if (!_overList.contains(memberName))
                  value = memberName; 
              } 
            } 
            if (value != null && CharObjidTable.get().charObjid(value) > 0) {
              try {
                L1ItemInstance item = ItemTable.get().createItem(56256);
                item.setCount(itemCount);
                DwarfReading.get().insertItem(CharacterTable.getAccountName(value), item);
              } catch (Exception e) {
                _log.error(e.getLocalizedMessage(), e);
              } 
              _overList.add(value);
            } 
            j++;
          } 
          i++;
        } 
        _checkList.clear();
        _overList.clear();
        ps = co.prepareStatement("DELETE FROM `server_board_orim` WHERE `time_order`<=?");
        ps.setTimestamp(1, timestamp);
        ps.execute();
      } catch (SQLException e2) {
        _log.error(e2.getLocalizedMessage(), e2);
      } finally {
        SQLUtil.close(ps);
        SQLUtil.close(co);
      } 
    } 
    try {
      co = DatabaseFactory.get().getConnection();
      ps = co.prepareStatement("SELECT * FROM `server_board_orim` ORDER BY `score` DESC");
      rs = ps.executeQuery();
      while (rs.next()) {
        int id = rs.getInt("id");
        if (id > _maxid)
          _maxid = id; 
        String[] partyMember2 = rs.getString("partyMember").split(",");
        List<String> checkList2 = new CopyOnWriteArrayList<>();
        String[] array2;
        int l = (array2 = partyMember2).length;
        int n2 = 0;
        while (n2 < l) {
          String str2 = array2[n2];
          checkList2.add(str2);
          n2++;
        } 
        String leader2 = rs.getString("leader");
        int score2 = rs.getInt("score");
        Iterator<L1Rank> iterator = _totalList.iterator();
        while (iterator.hasNext()) {
          L1Rank rank = iterator.next();
          if (leader2.equals(rank.getPartyLeader()) || rank.getPartyMember().contains(leader2)) {
            leader2 = null;
            break;
          } 
        } 
        Iterator<String> iterator2 = checkList2.iterator();
        while (iterator2.hasNext()) {
          String check_member = iterator2.next();
          Iterator<L1Rank> iterator4 = _totalList.iterator();
          while (iterator4.hasNext()) {
            L1Rank rank3 = iterator4.next();
            if (check_member.equals(rank3.getPartyLeader()) || 
              rank3.getPartyMember().contains(check_member)) {
              checkList2.remove(check_member);
              break;
            } 
          } 
        } 
        L1Rank rank4 = new L1Rank(leader2, checkList2, score2);
        _totalList.add(rank4);
      } 
    } catch (SQLException e3) {
      _log.error(e3.getLocalizedMessage(), e3);
    } finally {
      SQLUtil.close(rs);
      SQLUtil.close(ps);
      SQLUtil.close(co);
    } 
    _log.info("载入欧林布告栏资料数量: " + _totalList.size() + "(" + timer.get() + "ms)");
  }
  
  public List<L1Rank> getTotalList() {
    return _totalList;
  }
  
  public int writeTopic(int score, String leader, List<String> partyMember) {
    int length = partyMember.size();
    if (length <= 0)
      return 0; 
    StringBuilder sbr = new StringBuilder();
    int i = 0;
    while (true) {
      sbr.append(partyMember.get(i));
      if (++i >= length)
        break; 
      sbr.append(",");
    } 
    Connection co = null;
    PreparedStatement ps = null;
    try {
      co = DatabaseFactory.get().getConnection();
      ps = co.prepareStatement(
          "INSERT INTO `server_board_orim` SET `id`=?,`score`=?,`leader`=?,`partyMember`=?,`time_order`=?");
      ps.setInt(1, ++_maxid);
      ps.setInt(2, score);
      ps.setString(3, leader);
      ps.setString(4, sbr.toString());
      ps.setTimestamp(5, new Timestamp(System.currentTimeMillis()));
      ps.execute();
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(ps);
      SQLUtil.close(co);
    } 
    Iterator<L1Rank> iterator = _totalList.iterator();
    while (iterator.hasNext()) {
      L1Rank l1Rank = iterator.next();
      if (leader.equals(l1Rank.getPartyLeader()) || l1Rank.getPartyMember().contains(leader)) {
        leader = null;
        break;
      } 
    } 
    Iterator<String> iterator2 = partyMember.iterator();
    while (iterator2.hasNext()) {
      String check_member = iterator2.next();
      Iterator<L1Rank> iterator3 = _totalList.iterator();
      while (iterator3.hasNext()) {
        L1Rank rank2 = iterator3.next();
        if (check_member.equals(rank2.getPartyLeader()) || rank2.getPartyMember().contains(check_member)) {
          partyMember.remove(check_member);
          break;
        } 
      } 
    } 
    L1Rank rank = new L1Rank(leader, partyMember, score);
    int index = _totalList.size(), size = index;
    i = 0;
    while (i < size) {
      if (score > ((L1Rank)_totalList.get(i)).getScore()) {
        index = i;
        break;
      } 
      i++;
    } 
    _totalList.add(index, rank);
    return index + 1;
  }
  
  public void renewPcName(String oriName, String newName) {
    updateLeaderName(oriName, newName);
    Connection co = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
      co = DatabaseFactory.get().getConnection();
      ps = co.prepareStatement("SELECT * FROM `server_board_orim`");
      rs = ps.executeQuery();
      while (rs.next()) {
        String partyMember = rs.getString("partyMember");
        boolean checkOkay = false;
        String[] split;
        int length = (split = partyMember.split(",")).length;
        int i = 0;
        while (i < length) {
          String str = split[i];
          if (oriName.equals(str)) {
            checkOkay = true;
            break;
          } 
          i++;
        } 
        if (checkOkay)
          updateMemberName(partyMember, partyMember.replace(oriName, newName)); 
      } 
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(rs);
      SQLUtil.close(ps);
      SQLUtil.close(co);
    } 
    Iterator<L1Rank> iterator = _totalList.iterator();
    while (iterator.hasNext()) {
      L1Rank rank = iterator.next();
      if (oriName.equals(rank.getPartyLeader())) {
        rank.setPartyLeader(newName);
        continue;
      } 
      int index = rank.getPartyMember().indexOf(oriName);
      if (index < 0)
        continue; 
      rank.getPartyMember().set(index, newName);
    } 
  }
  
  private final void updateLeaderName(String oriName, String newName) {
    Connection co = null;
    PreparedStatement ps = null;
    try {
      co = DatabaseFactory.get().getConnection();
      ps = co.prepareStatement("UPDATE `server_board_orim` SET `leader`=? WHERE `leader`=?");
      ps.setString(1, newName);
      ps.setString(2, oriName);
      ps.execute();
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(ps);
      SQLUtil.close(co);
    } 
  }
  
  private final void updateMemberName(String oriName, String newName) {
    Connection co = null;
    PreparedStatement ps = null;
    try {
      co = DatabaseFactory.get().getConnection();
      ps = co.prepareStatement("UPDATE `server_board_orim` SET `partyMember`=? WHERE `partyMember`=?");
      ps.setString(1, newName);
      ps.setString(2, oriName);
      ps.execute();
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(ps);
      SQLUtil.close(co);
    } 
  }
}
